//
//  JYSetingPwdController.m
//  JYFarm
//
//  Created by 花花 on 2017/10/11.
//  Copyright © 2017年 花花. All rights reserved.
//

#import "JYSetingPwdController.h"
#import "JYSettingPwdView.h"
#import "JYLoginController.h"
#import "BaseNavViewController.h"
@interface JYSetingPwdController (){

    UIButton * _smsCodeBtn;
    
    BOOL _isSetingPwd;
}
@property(nonatomic)JYSettingPwdView *accountTextFiled;//用户名

@property(nonatomic)JYSettingPwdView *pwdTextField;//新密码

@property(nonatomic)JYSettingPwdView *rePwdTextField;//确认密码

@property(nonatomic)JYSettingPwdView *verificationTextField;//验证码

@property(nonatomic)UIView *bgView;
@end

@implementation JYSetingPwdController

- (instancetype)initWithIsSetingPwd:(BOOL)isSetingPwd{
    
    if (self = [super init]) {
        _isSetingPwd = isSetingPwd;
    }
    return self;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNav];
    
    [self setupSubView];

    
}
#pragma mark - setupNav
- (void)setupNav{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = _isSetingPwd?@"设置密码":@"修改密码";

}
- (void)setupSubView{

    CGFloat margin = 0;
    CGFloat height = kGlobalButtonHeight;
    CGFloat padding = 0;

    CGFloat bgViewHight = _isSetingPwd? height *4:height*3;
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, bgViewHight)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    _bgView = bgView;
    
    NSString *inputStr1 = _isSetingPwd?@"请输入手机号":@"请输入原密码";
    NSString *iconName1 = _isSetingPwd?@"login_mobile_number":@"login_password";
    
    
    //用户名
    self.accountTextFiled = [self registerFrame:CGRectMake(margin, 0, Screen_Width - margin *2 , height) placeholder:inputStr1 leftImgName:iconName1];
    
//    NSString *inputStr2 = _isSetingPwd?@"请输入新密码":@"请输入新密码";
//    NSString *iconName2 = _isSetingPwd?@"login_password":@"login_password";
    //密码
    self.pwdTextField = [self registerFrame:CGRectMake(margin, CGRectGetMaxY(self.accountTextFiled.frame)+padding,Screen_Width - margin *2 , height) placeholder:@"请输入新密码" leftImgName: @"login_password"];
    
    //确认密码
    self.rePwdTextField  = [self registerFrame:CGRectMake(margin, CGRectGetMaxY(self.pwdTextField.frame)+padding, Screen_Width - margin *2 , height) placeholder:@"请再次确认密码" leftImgName:@"login_password"];
    
    if (_isSetingPwd ==YES) {
        //请输入验证码
        self.verificationTextField =  [self registerFrame:CGRectMake(margin, CGRectGetMaxY(self.rePwdTextField.frame)+padding, Screen_Width - margin *2 , height) placeholder:@"请输入验证码" leftImgName:@"login_verification_code_icon"];
        self.verificationTextField.inputTextFiled.clearButtonMode = UITextFieldViewModeNever;
        [self.bgView addSubview:self.verificationTextField];
        //获取验证码
        
        UIButton *getSmsBtn =[UIButton jy_buttontitle:@"获取验证码" titleColor:kThemeColor frame:CGRectMake(Screen_Width -90-15,10 , 90, 30 ) target:self action:@selector(getsmsCodeBtnOnClick:) fontSize:14 bgImageName:@"login_verification_code"];
        getSmsBtn.tag = 10;
        [self.verificationTextField addSubview:getSmsBtn];
    }

    
    
    UIButton *confirmBtn = [UIButton jy_buttontitle:_isSetingPwd?@"确认":@"确认修改" titleColor:[UIColor whiteColor] frame:CGRectMake(10, CGRectGetMaxY(self.bgView.frame)+30, Screen_Width-20, kBtnHeight) target:self action:@selector(confirmOnClick:) fontSize:17 bgImageName:@"login_button_background"];
    [self.view addSubview:confirmBtn];

    
}

#pragma mark - SEL Methods
- (void)confirmOnClick:(UIButton *)btn{

    [self loadFormupdateUserLoginPassNeteork];
}


- (void)loadFormupdateUserLoginPassNeteork{

    if (![self checkParam]) {
        return;
    }
    if (_isSetingPwd) {
       
        if (self.verificationTextField.inputTextFiled.text.length == 0) {
            [MBProgressHUD LY_ShowError:(@"请输入验证码")time:2.0];
            return ;
        }
    }else{
    
         if (![self.pwdTextField.inputTextFiled.text isEqualToString:self.rePwdTextField.inputTextFiled.text]) {
            [MBProgressHUD LY_ShowError:(@"新密码和确认密码不一致") time:2.0];
            
            return;
        }

    }
    NSLog(@"userid%@",LH.userInfor.userid);
    NSString *oldPwd = self.pwdTextField.inputTextFiled.text;
    NSString *newPwd = self.rePwdTextField.inputTextFiled.text;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userid"] = _isSetingPwd?@"":LH.userInfor.userid;
    param[@"password"] =_isSetingPwd?[LYTools MD5ForLower32Bate:oldPwd]:[LYTools MD5ForLower32Bate:self.accountTextFiled.inputTextFiled.text];
    param[@"newPassword"] = [LYTools MD5ForLower32Bate:newPwd];
    //短信验证码 (有值 找回密码，没有值修改密码 )
    param[@"smsCode"] = _isSetingPwd? self.verificationTextField.inputTextFiled.text:@"";
    param[@"userName"] = _isSetingPwd?@"":@"18673556376";
    JYWeakSelf;
    [HTTPRequest POST:kUpdateUserLoginPassUrl parameter:param success:^(id resposeObject) {
    
        if (SUCCESS) {
            
            if (!_isSetingPwd) {
                
          JYLoginController *loginVc = [[JYLoginController  alloc]init];
          BaseNavViewController *nav = [[BaseNavViewController alloc]initWithRootViewController:loginVc];
          [weakSelf presentViewController:nav animated:YES completion:nil];
                
              }
            
            
        }else{
            [MBProgressHUD LY_ShowError:(resposeObject[@"msg"]) time:2.0];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD LY_ShowError:(kNoNetworkTips) time:2.0];
    }];
    
    

}

- (void)getsmsCodeBtnOnClick:(UIButton *)btn{
    
    
    if (![self checkParam]) {
        return;
    }
 

    [self sendCodeEvent:btn];//发送验证码
}
//获取验证码
#pragma mark - loadData sendCode
- (void)sendCodeEvent:(UIButton *)btn{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] =  self.accountTextFiled.inputTextFiled.text;
    //操作类型(0登录1注册 2找回密)
    param[@"operateType"]= @"1";
    
    [HTTPRequest POST:kGetSmsCodeUrl parameter:param success:^(id resposeObject) {
        
        NSLog(@"发送验证码……%@",resposeObject);
        
        if (SUCCESS) {
            
            [self getPhoneCode:btn];
            
        }else{
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
            
        }
    } failure:^(NSError *error) {
        
        [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];
        
    }];
    
    
}
- (void)getPhoneCode:(UIButton *)btn{
    __block int MaxTime =kGlobalGetVaildCodeTime;
    _smsCodeBtn = btn;
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (MaxTime<=0) {
            dispatch_source_cancel(_timer);
            //dispatch_release(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //倒计时结束
                _smsCodeBtn =(UIButton*)[self.view viewWithTag:10];
                [_smsCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
                [_smsCodeBtn setUserInteractionEnabled:YES];
                
                [_smsCodeBtn setTitleColor: [UIColor whiteColor]forState:UIControlStateNormal];
//                [_smsCodeBtn setBackgroundColor:[UIColor colorWithHexString:@"FF7E37"]];
                
            });
        }else{
            NSString* strTime=[NSString stringWithFormat:@"%d s ",(int)(MaxTime)];
            dispatch_async(dispatch_get_main_queue(), ^{
                //倒计时
                _smsCodeBtn=(UIButton*)[self.view viewWithTag:10];
                [_smsCodeBtn setTitle:strTime forState:UIControlStateNormal];
                
//                _smsCodeBtn.backgroundColor =[UIColor colorWithHexString:@"b1b1b1"];
                [_smsCodeBtn setUserInteractionEnabled:NO];
            });
            MaxTime--;
        }
    });
    dispatch_resume(_timer);
    
}
#pragma mark - checkParam
- (BOOL)checkParam{
    NSString *oldPwd = self.accountTextFiled.inputTextFiled.text;
    NSString *newPwd = self.pwdTextField.inputTextFiled.text;
    if(!_isSetingPwd){
    
        if(oldPwd.length == 0 ){
        [MBProgressHUD LY_ShowError:(@"请输入原密码") time:2.0];
        return NO;
         
        }else if(newPwd.length == 0 ){
        [MBProgressHUD LY_ShowError:(@"请输入新密码") time:2.0];
        return NO;
        
        
        }else if (self.rePwdTextField.inputTextFiled.text.length == 0){
            
            [MBProgressHUD LY_ShowError:(@"请再次输入确认密码") time:2.0];
            return NO;
      
        }
    }else{
        if (self.accountTextFiled.inputTextFiled.text.length == 0) {
            [MBProgressHUD LY_ShowError:(@"请输入手机号")time:2.0];
            return NO;
            
        }else if (![self.accountTextFiled.inputTextFiled.text isMobileNumber]){
            
            [MBProgressHUD LY_ShowError:(@"请输入正确的手机号")time:2.0];
            return NO;
            
        }else if(self.pwdTextField.inputTextFiled.text.length == 0){
            //        (self.pwdTextField.inputTextFiled.text.length < 6 || self.pwdTextField.inputTextFiled.text.length > 18) {
            //           [MBProgressHUD LY_ShowError:(@"密码不符合要求,请重新输入") time:2.0];
            [MBProgressHUD LY_ShowError:(@"请输入新密码") time:2.0];
            return NO;
        }else if (self.rePwdTextField.inputTextFiled.text.length == 0){
        
            [MBProgressHUD LY_ShowError:(@"请再次输入确认密码") time:2.0];
            return NO;
        }
        
        
    }
    return YES;
}

- (JYSettingPwdView *)registerFrame:(CGRect)frame placeholder:(NSString *)placeholder leftImgName:(NSString *)leftImgName{
    
    JYSettingPwdView *regiseter = [[JYSettingPwdView alloc] initWithFrame:frame];
    regiseter.inputTextFiled.placeholder = placeholder;
    regiseter.imgView.image = [UIImage imageNamed:leftImgName];
    [self.bgView addSubview:regiseter];
    
    return regiseter;
    
    
}


@end
